package com.design.reactor.stretchIO._1_singleReactorSingleThread.impl.handler;

import java.io.IOException;
import java.nio.channels.*;

public class AcceptHandler extends AbstractHandler {

    public AcceptHandler()  {  }

    public AcceptHandler(Selector selector, ServerSocketChannel socketChannel) throws IOException {
        socketChannel.configureBlocking(false);
        // 也可以注解注册SelectionKey.OP_READ; 这里先不关心任何事件， 后面注册读事件
        SelectionKey selectionKey = socketChannel.register(selector, 0);//注册一个不存在的事件
        selectionKey.attach(this);
        selectionKey.interestOps(SelectionKey.OP_ACCEPT);//将此键的 interest 集合设置为给定值 ： 注册读事件
        selector.wakeup();//唤醒前一个阻塞的socket
    }

    @Override
    public void handle(Selector selector , SelectableChannel channel, SelectionKey selectionKey) {
        try{
            if(selectionKey.isAcceptable()){
                System.out.println("--- AcceptHandler 接受客户端请求！！ " );
                SocketChannel socketChannel = ((ServerSocketChannel)channel).accept();
                if(socketChannel!=null) {
                    new ReaderHandler(selector,socketChannel);
                }
            }
        }catch (Exception e){
            selectionKey.cancel();
        }
    }
}
